<template>
	<view class="pageBox">
		<!-- 注意，如果需要兼容微信小程序，最好通过setRules方法设置rules规则 -->
		<u--form labelPosition="left" :model="userInfo" :rules="rules" ref="uForm" labelWidth="160rpx">
			<u-form-item label="姓名" prop="name" borderBottom>
				<u--input v-model="userInfo.name" border="none" placeholder="请填写姓名"></u--input>
			</u-form-item>
			<u-form-item label="性别" prop="sexLabel" borderBottom>
				<u--input v-model="userInfo.sexLabel" disabled disabledColor="#ffffff" placeholder="请选择性别"
					border="none"></u--input>
				<u-icon slot="right" name="arrow-right"></u-icon>
				<view class="inputClick" @click.stop="openPicker('sys_user_sex','sex','请选择性别')"></view>
			</u-form-item>
			<u-form-item label="手机号码" prop="phonenumber" borderBottom>
				<u--input v-model="userInfo.phonenumber" placeholder="请输入手机号码" border="none"></u--input>
			</u-form-item>
			<u-form-item label="出生日期" prop="birthLabel" borderBottom @click="openDatetime">
				<u--input v-model="userInfo.birthLabel" disabled disabledColor="#ffffff" placeholder="请选择出生日期"
					border="none"></u--input>
				<u-icon slot="right" name="arrow-right"></u-icon>
				<view class="inputClick" @click="openDatetime"></view>
			</u-form-item>
			<u-form-item label="身份证" prop="idCard" borderBottom>
				<u--input v-model="userInfo.idCard" placeholder="请输入身份证号" border="none"></u--input>
			</u-form-item>
			<u-form-item label="人才类型" prop="eliteTypeLabel" borderBottom
				@click="openPicker('elite_type','eliteType','请选择人才类型')">
				<u--input v-model="userInfo.eliteTypeLabel" disabled disabledColor="#ffffff" placeholder="请选择人才类型"
					border="none"></u--input>
				<u-icon slot="right" name="arrow-right"></u-icon>
				<view class="inputClick" @click="openPicker('elite_type','eliteType','请选择人才类型')"></view>
			</u-form-item>
			<u-form-item label="材料证明" prop="certificationMaterial" borderBottom>
				<!-- <u--input v-model="userInfo.idCard" placeholder="请输入身份证号" border="none"></u--input> -->
				<u-upload width="160rpx" height="160rpx" :fileList="fileList" @afterRead="afterRead($event, 'fileList')"
					@delete="deletePic($event, 'fileList')" multiple accept="image">
				</u-upload>
			</u-form-item>
			<u-form-item label="备注" prop="remark" borderBottom>
				<u--input v-model="userInfo.remark" placeholder="请输入备注" border="none"></u--input>
			</u-form-item>
			<view style="margin-top: 80rpx;"></view>
			<u-button @click="submit" shape="circle" type="primary">提交</u-button>
		</u--form>
		<myPicker :show="pickerShow" :columns="[actions]" :title="pickerTitle"
			@confirm="confirm($event,'value','label')" @close="closePicker('pickerShow')"
			@cancel="closePicker('pickerShow')"></myPicker>
		<u-datetime-picker :minDate="-4607395543000" ref="datetimePicker" :show="datetimeShow" v-model="datetimeValue"
			mode="date" @confirm="datetimeConfirm" @close="closePicker('datetimeShow')"
			@cancel="closePicker('datetimeShow')"></u-datetime-picker>
	</view>
</template>

<script>
	import {
		certification
	} from "@/api/certification.js"
	import * as util from "@/utils/util.js";
	import {
		dictDataList
	} from "@/api/system.js"
	import * as uploadApi from "@/api/upload.js"
	export default {
		data() {
			return {
				userInfo: {
					"remark": "",
					"sexLabel": '',
					"name": "",
					"sex": "",
					"birth": "",
					"birthLabel": "",
					// "phonenumber": "",
					"idCard": "",
					"eliteType": "",
					"eliteTypeLabel": '',
					"certificationMaterial": "",
				},
				IMGMaxSize: 1024 * 1024 * 5,
				fileList: [],
				fileList_imgs: [],
				fileList_old: [],
				actions: ['男', '女', ],
				rules: {
					'name': {
						type: 'string',
						required: true,
						message: '请填写姓名',
						trigger: ['blur', 'change']
					},
					'sexLabel': {
						type: 'string',
						max: 1,
						required: true,
						message: '请选择男或女',
						trigger: ['blur', 'change']
					},
					'phonenumber': [{
							required: true,
							message: '请输入手机号',
							trigger: ['change', 'blur'],
						},
						{
							// 自定义验证函数，见上说明
							validator: (rule, value, callback) => {
								// 上面有说，返回true表示校验通过，返回false表示不通过
								// uni.$u.test.mobile()就是返回true或者false的
								return uni.$u.test.mobile(value);
							},
							message: '手机号码不正确',
							// 触发器可以同时用blur和change
							trigger: ['change', 'blur'],
						}
					],
					'idCard': [{
							required: true,
							message: '请输入身份证号码',
							trigger: ['change', 'blur'],
						},
						{
							// 自定义验证函数，见上说明
							validator: (rule, value, callback) => {
								console.log(uni.$u.test.idCard(value));
								return uni.$u.test.idCard(value);
							},
							message: '身份证号码不正确',
							// 触发器可以同时用blur和change
							trigger: ['change', 'blur'],
						}
					],
					'eliteTypeLabel': {
						type: 'string',
						required: true,
						message: '请选择人才类型',
						trigger: ['blur', 'change']
					},
					'birthLabel': {
						type: 'string',
						required: true,
						message: '请选择出生日期',
						trigger: ['blur', 'change']
					},
					'certificationMaterial': {
						type: 'string',
						required: true,
						message: '请上传材料证明',
						trigger: ['blur', 'change']
					},
				},
				radio: '',
				switchVal: false,
				datetimeShow: false,
				datetimeValue: Number(new Date()),
				dicts: {
					sys_user_sex: {},
					elite_type: {}
				},
				dictList: {
					sys_user_sex: [],
					elite_type: []
				},
				openName: '',
				pickerTitle: '',
				pickerShow: false,
			};
		},
		mounted() {
			this.getDictDataList('elite_type')
			this.getDictDataList('sys_user_sex')
			console.log(new Date("1824-1-1").getTime());
		},
		methods: {
			deletePic(event, dataStr) {
				this[dataStr].splice(event.index, 1)
				if (typeof(this[dataStr + '_imgs']) === 'string') {
					this[dataStr + '_imgs'] = ''
				} else {
					this[dataStr + '_imgs'].splice(event.index, 1)
				}
				console.log(this[dataStr + '_imgs'])
			},
			beforeRead(file, lists) {
				// const {
				// 	name,
				// 	size,
				// 	type
				// } = file
				const imgTypes = ['bmp', 'jpg', 'png', 'jpeg']
				const IMGMaxSize = this.IMGMaxSize
				file.forEach(item => {
					const isJPG = imgTypes.indexOf(item.type) !== -1;
					const sizeT = item.size <= IMGMaxSize
				})
				console.log(file, lists);
				return sizeT && isJPG
			},
			// 新增图片
			async afterRead(event, dataStr) {
				console.log(event, dataStr)
				const that = this
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[dataStr].length
				//备份 失败回调
				that[dataStr + '_old'] = JSON.parse(JSON.stringify(that[dataStr]))
				lists.map(item => {
					that[dataStr].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await that
						.uploadFilePromise(lists[i].url, dataStr)
						.then(res => {
							return res
						})
						.catch(() => {
							// that[dataStr] = that[dataStr + '_old']
							return false
						})
					if (result) {
						let item = that[dataStr][fileListLen]
						that[dataStr].splice(
							fileListLen,
							1,
							Object.assign(item, {
								status: 'success',
								message: '',
								url: result.url
							})
						)
						fileListLen++
					} else {
						let item = that[dataStr][fileListLen]
						that[dataStr].splice(
							fileListLen,
							1
						)
					}
					that[dataStr + '_old'] = JSON.parse(JSON.stringify(that[dataStr]))
				}
			},
			uploadFilePromise(url, dataStr) {
				return new Promise((resolve, reject) => {
					uploadApi
						.upload(url)
						.then((
							data
						) => {
							console.log(data)
							const {
								fileName,
								newFileName,
								originalFilename,
								url
							} = data
							const imgData = {
								fileName,
								newFileName,
								originalFilename,
								url
							}
							if (Object.prototype.toString.call(this[dataStr + '_imgs']) ===
								'[object Array]') {
								this[dataStr + '_imgs'].push(imgData)
							} else if (Object.prototype.toString.call(this[dataStr + '_imgs']) ===
								'[object String]') {
								this[dataStr + '_imgs'] = imgData
							}
							resolve(imgData)
						})
						.catch(reject)
				})
			},
			getDictDataList(dictType) {
				return new Promise((resolve, reject) => {
					dictDataList(dictType).then(({
						rows
					}) => {
						let objs = {}
						let keyValues = []
						rows.forEach((item) => {
							objs[item.dictValue] = item.dictLabel
							keyValues.push({
								label: item.dictLabel,
								text: item.dictLabel,
								value: item.dictValue
							})
						})
						this.dicts[dictType] = objs
						this.dictList[dictType] = keyValues
						resolve({
							objs,
							keyValues,
							rows
						})
					}).catch(reject)
				})
			},
			openPicker(arrName, dataName, title) {
				this.pickerTitle = title
				this.actions = this.dictList[arrName]
				this.pickerShow = true
				this.openName = dataName
			},
			confirm(e, keyName = '', labelName = '') {
				const openName = this.openName
				if (keyName) {
					this.userInfo[openName] = e.value[0][keyName]
					this.userInfo[openName + 'Label'] = e.value[0][labelName]
				} else {
					this.userInfo[openName] = e.indexs[0]
					this.userInfo[openName + 'Label'] = e.value[0]
				}
				this.pickerShow = false
				console.log(e);
			},
			closePicker(showName) {
				this[showName] = false
			},
			dateFormat(time, format = "YYYY-mm-dd") {
				return util.dateFormat(time, format)
			},
			openDatetime(name) {
				this.datetimeShow = true
				this.openName = name
			},
			datetimeConfirm({
				mode,
				value
			}) {
				// this.$set(this.userInfo, openName, value)
				this.userInfo.birth = value
				this.userInfo.birthLabel = this.dateFormat(value)
				this.datetimeShow = false
				console.log(this.userInfo.birth);
			},
			formatter(type, value) {
				if (type === 'year') {
					return `${value}年`
				}
				if (type === 'month') {
					return `${value}月`
				}
				if (type === 'day') {
					return `${value}日`
				}
				return value
			},
			submit() {
				const that = this
				if (this.fileList.length > 0) {
					this.userInfo.certificationMaterial = JSON.stringify(this.fileList)
				}
				this.$refs.uForm.validate().then(res => {
					const fromData = JSON.parse(JSON.stringify(this.userInfo))
					uni.$u.throttle(
						certification(fromData).then(res => {
							that.$toast1("操作成功", () => {
								setTimeout(() => {
									uni.reLaunch({
										url: '/pages/index/index'
									})
								}, 500)
							})

						}), 1000)
				}).catch(errors => {
					this.userInfo.certificationMaterial = ''
					// uni.$u.toast('校验失败')
				})
			},
			sexSelect(e) {
				this.userInfo.sex = e.name
				this.$refs.uForm.validateField('sex')
			},
		},
		onReady() {
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
			this.$refs.uForm.setRules(this.rules)
		},
	};
</script>
<style lang="scss" scoped>
	.pageBox {
		padding: 0 30rpx;

		/deep/ .u-form-item {
			position: relative;

		}

		.inputClick {
			width: 100%;
			height: 100%;
			position: absolute;
			left: 0;
			top: 0;
		}

		.button {
			background: linear-gradient(90deg, #5F96E8 0%, #1977E1 100%);
		}
	}
</style>